#!/usr/bin/env python3
# encoding=utf-8
import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from commom_api import get_sec_info
import logging
logger = logging.getLogger(__name__)

def create_msg_base(sendby, sendto, subject):
    msg = MIMEMultipart()
    msg['From'] = sendby
    msg['To'] = 'receiver@example.com'
    msg['Subject'] = subject
    return msg

def add_content_to_msg(msg, content):
    html_content = f"""
    <p>{content}<br>
    """
    msg.attach(MIMEText(html_content, 'html', 'utf-8'))
    return msg

def add_picture_to_msg(msg, picpath, content=None):
    picid = os.path.basename(picpath)
    if content != None:
        html_content = f"""
        <p>{content}<br>
        <img src="cid:{picid}"></p>
        """
    else:
        html_content = f"""
        <img src="cid:{picid}"></p>
        """
    msg.attach(MIMEText(html_content, 'html', 'utf-8'))
    
    with open(picpath, "rb") as img_file:
        img = MIMEImage(img_file.read())
        img.add_header('Content-ID', f'<{picid}>')  # 与 HTML 中的 cid 对应
        msg.attach(img)
    return msg

def add_file_to_msg(msg, filepath):
    filename = os.path.basename(filepath)
    with open(filepath, "rb") as file:
        part = MIMEApplication(file.read(), Name=filename)
        part['Content-Disposition'] = f'attachment; filename="{filename}"'
        msg.attach(part)
    return msg

def send_msg_with_smtp(msg):
    print(msg)
    try:
        with smtplib.SMTP_SSL('smtp.qq.com', 465) as server:
            server.login('sender@example.com', 'your_auth_code')
            server.sendmail(msg['From'], msg['To'], msg.as_string())
        print("邮件发送成功！")
    except Exception as e:
        print(f"发送失败: {e}")


if __name__=="__main__":
    get_data_by_pop()